import time, sys
from tinynl import *

def ping_client(port):
  ms = Client('', port)
  assert ms.get_blocking() == 'go!'
  t0 = time.time()
  for i in range(1, 10000):
    ms.send('ping %d' % i)
    resp = ms.get_blocking(5)
    assert resp == 'pong %d' %i, 'response == %s' % resp
  dt = time.time() - t0
  print 'dt = %.2f, ping = %.3f or %.2f Hz' % (dt, dt/i, 1/(dt/i))
  ms.send('Hz %.3f' % (1/(dt/i)))

def main():
  server = Server()
  port = server.port

  NCLIENTS = 10
  for ci in range(NCLIENTS):
    # start client in separate thread
    t = threading.Thread(target=ping_client, args=(port,))
    t.setDaemon(True); t.start()

  clients = []
  pings = []
  while len(clients) < NCLIENTS:
    for c in server.new_clients():
      clients.append(c)
      print '%d clients connected' % len(clients)
  print 'starting clients ;)'
  print '#threads == %d' % threading.active_count()
  for c in clients:
    c.send('go!')
  while len(clients) > 0:
    for c in clients:
      msgs = c.get()
      if msgs != []:
        assert len(msgs) == 1
        cmd, n = msgs[0].split()
        if cmd == 'ping':
          c.send('pong %d' % int(n))
        if cmd == 'Hz':
          pings.append(float(n))
          clients.remove(c)
    time.sleep(0)
  print 'avg freq: %.2f, sum freq: %.2f' % (sum(pings) / float(len(pings)), 
    sum(pings))
  
if __name__ == '__main__':
  logging.basicConfig(level=logging.INFO)
  main()
